package com.uit.trip_.tab_activity;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.uit.trip_.R;
import com.uit.trip_.TripApplication;
import com.uit.trip_.data.TripDatabase;
import com.uit.trip_.models.LocationModel;
import com.uit.trip_.models.WallAppItem;
import com.uit.trip_.models.WallMenuItem;
import com.uit.trip_.tab_activity.childs.WallItemDetailActivity;
import com.uit.trip_.utils.ProcessImage;
import com.uit.trip_.utils.ViewUtils;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.location.Location;
import android.media.audiofx.AudioEffect.OnControlStatusChangeListener;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnCreateContextMenuListener;
import android.view.ViewGroup;
import android.view.Window;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.view.animation.Animation.AnimationListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class Tab_TripWallActivity extends Activity implements AnimationListener {

	private static final String TAG = "wall";
	private static final int WALL_DETAIL_REQUESTCODE = 10;
	private TripDatabase db;
	View menu;
	View app;
	boolean menuOut = false;
	AnimParams animParams = new AnimParams();
	private ListView listViewContent;
	private ListView listViewHeader;
	private ImageButton btSlide;
	private ImageButton btAddNewSub;
	private List<WallMenuItem> menuList;
	private MenuAdapter menuAdapter;
	private View menuHeader;
	private View appHeader;
	private AppAdapter appAdapter;
	private List<WallAppItem> appList;
	private Boolean isAnimation = false;
	private WallMenuItem currentMenuItem;

	/*
	 * Ham xu ly activity
	 */
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.tab_wall);

		menu = findViewById(R.id.menu);
		app = findViewById(R.id.app);

		db = new TripDatabase(this);
		currentMenuItem = null;
		listViewContent = (ListView) app.findViewById(R.id.listContent);
		listViewHeader = (ListView) menu.findViewById(R.id.listmenu);
		listViewContent
				.setOnCreateContextMenuListener(createAppContextMenuListener);
		listViewHeader
				.setOnCreateContextMenuListener(createMenuContextMenuListener);
		// listViewContent.setOnItemLongClickListener(appItemLongClickListener);
		menuList = new ArrayList<WallMenuItem>();
		menuAdapter = new MenuAdapter();
		LayoutInflater layoutInflater = getLayoutInflater();

		// Config empty view
		// View emptyView = layoutInflater.inflate(R.layout.listview_empty,
		// listViewContent, false);
		// listViewContent.setEmptyView(emptyView);
		// emptyView = layoutInflater.inflate(R.layout.listview_empty,
		// listViewHeader, false);
		// listViewHeader.setEmptyView(emptyView);

		// Config for left menu
		menuHeader = layoutInflater.inflate(R.layout.wall_row_left_header,
				listViewHeader, false);
		listViewHeader.addHeaderView(menuHeader);
		ImageButton btAddNewMenu = (ImageButton) menuHeader
				.findViewById(R.id.btAddMenuItem);

		btAddNewMenu.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				reAnimation(0);
				showAddNewMenuItemDialog();
			}
		});

		// Config app
		appAdapter = new AppAdapter();
		appHeader = layoutInflater.inflate(R.layout.wall_row_right_header,
				listViewContent, false);
		listViewContent.addHeaderView(appHeader);

		appList = new ArrayList<WallAppItem>();
		listViewContent.setAdapter(appAdapter);
		listViewContent.setOnItemClickListener(appItemClickListener);

		btSlide = (ImageButton) app.findViewById(R.id.BtnSlide);
		btSlide.setOnClickListener(new ClickListener());
		btAddNewSub = (ImageButton) app.findViewById(R.id.add_new_subItem);
		btAddNewSub.setOnClickListener(addNewItemClickListener);

		getMenuList();
		if (menuList.size() > 0) {
			currentMenuItem = menuList.get(0);
			getAppList(currentMenuItem.id);
		} else {
			updateAppHeader();
		}

		listViewHeader.setAdapter(menuAdapter);
		listViewHeader.setOnItemClickListener(menuItemClickListener);

	}

	@Override
	protected Dialog onCreateDialog(int id) {
		// TODO Auto-generated method stub

		switch (id) {
		case 0:

			break;
		case 1:

			break;
		default:
			break;
		}
		return null;
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		Log.i(TAG, "onResume");
		reAnimation(100);
	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		Log.i(TAG, "onPause");
		reAnimation(200);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == WALL_DETAIL_REQUESTCODE && resultCode == RESULT_OK) {
			// update lai view row
			appList.clear();
			getAppList(currentMenuItem.id);
			appAdapter.notifyDataSetChanged();
		}
	}

	/*
	 * Ham xu ly cho animation
	 */
	@Override
	public void onAnimationEnd(Animation arg0) {
		// TODO Auto-generated method stub
		menuOut = !menuOut;
		if (!menuOut) {
			menu.setVisibility(View.INVISIBLE);
		}
		layoutApp(menuOut);
	}

	@Override
	public void onAnimationRepeat(Animation arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onAnimationStart(Animation arg0) {
		// TODO Auto-generated method stub

	}

	private void reAnimation(long duration) {
		if (isAnimation) {
			animation(duration);
			isAnimation = false;
		}
	}

	private void animation(long duration) {
		Tab_TripWallActivity me = Tab_TripWallActivity.this;
		Context context = me;
		Animation anim;

		int w = app.getMeasuredWidth();
		int h = app.getMeasuredHeight();
		int left = (int) (app.getMeasuredWidth() * 0.8);

		if (!menuOut) {
			// anim = AnimationUtils.loadAnimation(context,
			// R.anim.push_right_out_80);
			anim = new TranslateAnimation(0, left, 0, 0);
			menu.setVisibility(View.VISIBLE);
			animParams.init(left, 0, left + w, h);
		} else {
			// anim = AnimationUtils.loadAnimation(context,
			// R.anim.push_left_in_80);
			anim = new TranslateAnimation(0, -left, 0, 0);
			animParams.init(0, 0, w, h);
		}

		anim.setDuration(duration);
		anim.setAnimationListener(me);
		// Tell the animation to stay as it ended (we are going to set the
		// app.layout first than remove this property)
		anim.setFillAfter(true);

		// Only use fillEnabled and fillAfter if we don't call layout
		// ourselves.
		// We need to do the layout ourselves and not use fillEnabled and
		// fillAfter because when the anim is finished
		// although the View appears to have moved, it is actually just a
		// drawing effect and the View hasn't moved.
		// Therefore clicking on the screen where the button appears does
		// not work, but clicking where the View *was* does
		// work.
		anim.setFillEnabled(true);
		// anim.setFillAfter(true);

		app.startAnimation(anim);
	}

	static class AnimParams {
		int left, right, top, bottom;

		void init(int left, int top, int right, int bottom) {
			this.left = left;
			this.top = top;
			this.right = right;
			this.bottom = bottom;
		}
	}

	void layoutApp(boolean menuOut) {
		app.layout(animParams.left, animParams.top, animParams.right,
				animParams.bottom);
		// Now that we've set the app.layout property we can clear the
		// animation, flicker avoided :)
		app.clearAnimation();

	}

	class ClickListener implements OnClickListener {
		@Override
		public void onClick(View v) {
			if (isAnimation) {
				isAnimation = false;
			} else {
				isAnimation = true;
			}
			animation(500);
		}
	}

	/*
	 * Ham xu ly cho menu
	 */
	private class MenuAdapter extends BaseAdapter {

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return menuList.size();
		}

		@Override
		public Object getItem(int arg0) {
			// TODO Auto-generated method stub
			return menuList.get(arg0);
		}

		@Override
		public long getItemId(int arg0) {
			// TODO Auto-generated method stub
			return arg0;
		}

		@Override
		public View getView(int arg0, View arg1, ViewGroup arg2) {
			// TODO Auto-generated method stub
			WallMenuItem item = menuList.get(arg0);
			LayoutInflater inflater = getLayoutInflater();
			View menuItem;

			if (arg1 == null) {
				menuItem = inflater.inflate(R.layout.wall_menu_item, arg2,
						false);
			} else {
				menuItem = arg1;
			}

			TextView tvItemName = (TextView) menuItem
					.findViewById(R.id.tvMenuName);
			TextView tvSubName = (TextView) menuItem
					.findViewById(R.id.tvMenuSubName);

			tvItemName.setText(item.itemName.toUpperCase());
			tvSubName.setText(item.itemDate);
			return menuItem;
		}
	}

	private void getMenuList() {
		// for (int i = 0; i < size; i++) {
		// String timeStamp = new SimpleDateFormat("yyyy-MM-dd HH:mm")
		// .format(new Date());
		// WallMenuItem item = new WallMenuItem("Trip NO." + i, "ha ha",
		// timeStamp);
		// menuList.add(item);
		// }
		menuList = db.getListTrips();
	}

	private OnItemClickListener menuItemClickListener = new OnItemClickListener() {

		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position,
				long id) {
			// TODO Auto-generated method stub
			if (position == 0)
				return;
			reAnimation(0);
			int index = position - 1;
			WallMenuItem item = menuList.get(index);
			currentMenuItem = item;
			getAppList(currentMenuItem.id);
		}
	};

	private OnCreateContextMenuListener createMenuContextMenuListener = new OnCreateContextMenuListener() {

		@Override
		public void onCreateContextMenu(ContextMenu menu, View v,
				ContextMenuInfo menuInfo) {
			// TODO Auto-generated method stub
			menu.setHeaderTitle("Trip");
			menu.add(0, 1, 0, "Delete Trip");
		}
	};

	private void showAddNewMenuItemDialog() {
		final Dialog dialog = new Dialog(this);
		dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
		dialog.setContentView(R.layout.add_new_menu);
		ImageButton btAdd = (ImageButton) dialog
				.findViewById(R.id.btAddMenuItem2);
		ImageButton btCacel = (ImageButton) dialog
				.findViewById(R.id.btCancelMenuItem2);
		final EditText etName = (EditText) dialog
				.findViewById(R.id.etMenuNameDialog);
		final EditText etDescription = (EditText) dialog
				.findViewById(R.id.etMenuDescriptionDialog);
		btAdd.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				// InputMethodManager imm = (InputMethodManager)
				// getSystemService(Context.INPUT_METHOD_SERVICE);
				// imm.hideSoftInputFromWindow(etDescription.getWindowToken(),
				// 0);
				String name = etName.getText().toString();
				if (name.equals("")) {
					name = "Trip " + menuList.size();
				}
				String timeStamp = new SimpleDateFormat("yyyy-MM-dd HH:mm")
						.format(new Date());
				WallMenuItem item = new WallMenuItem(name, etDescription
						.getText().toString(), timeStamp);
				Long id = db.insertToTrip(item);
				// Them id moi khi add phan tu moi
				item.id = id.intValue();
				menuList.add(item);
				menuAdapter.notifyDataSetChanged();
				updateAppHeader();
				currentMenuItem = item;
				getAppList(currentMenuItem.id);
				dialog.dismiss();
				// animation(500);
				// isAnimation = true;
				appAdapter.notifyDataSetChanged();

				etName.setText("");
				etDescription.setText("");
				dialog.cancel();
			}
		});
		btCacel.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				etName.setText("");
				etDescription.setText("");
				dialog.cancel();
			}
		});
		dialog.show();
	}

	/*
	 * Ham xu ly cho app content
	 */

	private class AppAdapter extends BaseAdapter {

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return appList.size();
		}

		@Override
		public Object getItem(int arg0) {
			// TODO Auto-generated method stub
			return appList.get(arg0);
		}

		@Override
		public long getItemId(int arg0) {
			// TODO Auto-generated method stub
			return arg0;
		}

		@Override
		public View getView(int arg0, View arg1, ViewGroup arg2) {
			// TODO Auto-generated method stub

			WallAppItem item = appList.get(arg0);
			View row;
			LayoutInflater inflater = getLayoutInflater();
			if (arg1 == null) {
				row = inflater.inflate(R.layout.wall_app_item, arg2, false);
			} else {
				row = arg1;
			}
			ImageView imgContent = (ImageView) row
					.findViewById(R.id.imgAppContent);

			TextView tvContent = (TextView) row
					.findViewById(R.id.tvAppRowContent);
			tvContent.setText(item.content);

			TextView tvAddress = (TextView) row
					.findViewById(R.id.tvAddressAppItem);
			if (!item.address.equalsIgnoreCase("")) {
				tvAddress.setText("At " + item.address);
			} else {
				tvAddress.setText("");
			}

			if (item.imagePath != null && !item.imagePath.equalsIgnoreCase("")) {
				BitmapFactory.Options bounds = new BitmapFactory.Options();
				bounds.inSampleSize = 4;
				Bitmap bm = BitmapFactory.decodeFile(item.imagePath, bounds);

				imgContent.setImageBitmap(bm);
			} else {
				imgContent.setImageResource(R.drawable.add_image);
			}
			return row;
		}
	}

	private void getAppList(int id) {
		appList.clear();
		appList = db.getListNoteById(id);
		appAdapter.notifyDataSetChanged();
		setContentAppHeader(currentMenuItem);
	}

	private void updateAppHeader() {
		if (menuList.size() == 0) {
			btAddNewSub.setEnabled(false);
			listViewContent.setVisibility(View.GONE);
		} else {
			btAddNewSub.setEnabled(true);
			listViewContent.setVisibility(View.VISIBLE);
		}
	}

	private OnItemClickListener appItemClickListener = new OnItemClickListener() {

		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position,
				long id) {
			// TODO Auto-generated method stub
			if (position == 0)
				return;
			int index = position - 1;

			WallAppItem item = appList.get(index);
			Intent i = new Intent(getApplicationContext(),
					WallItemDetailActivity.class);
			i.putExtra("position", index);
			i.putExtra("id", item.id);
			i.putExtra("id_trip", item.id_trip);
			i.putExtra("name", item.content);
			i.putExtra("address", item.address);
			i.putExtra("imagePath", item.imagePath);
			startActivityForResult(i, WALL_DETAIL_REQUESTCODE);
		}
	};

	// Khi chon menu item, goi ham nay de update lai content
	private void setContentAppHeader(WallMenuItem item) {

		TextView tvName = (TextView) appHeader.findViewById(R.id.tvAppName);
		TextView tvDescription = (TextView) appHeader
				.findViewById(R.id.tvAppDescription);
		TextView tvDate = (TextView) appHeader.findViewById(R.id.tvAppDate);

		tvName.setText(item.itemName.toUpperCase());
		tvDescription.setText(item.itemDesription);
		tvDate.setText(item.itemDate);

		//
	}

	private OnClickListener addNewItemClickListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			showAddnewAppItemDialog();
		}
	};

	public void showAddnewAppItemDialog() {
		final Dialog dialog = new Dialog(this);
		dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);

		TripApplication app = (TripApplication) getApplication();
		LocationModel currentLocation = app.getLocation();
		dialog.setContentView(R.layout.add_new_sub_item);
		final EditText etAddress = (EditText) dialog
				.findViewById(R.id.etItemAddress);
		currentLocation.address = "Binh dinh";
		Log.i("addnew", "case1:" + currentLocation.address);

		if (currentLocation.address != null) {
			etAddress.setText(currentLocation.address);
		}

		final EditText etContent = (EditText) dialog
				.findViewById(R.id.etItemContent);
		ImageButton btAdd1 = (ImageButton) dialog
				.findViewById(R.id.btAddMenuItem1);
		ImageButton btCancel1 = (ImageButton) dialog
				.findViewById(R.id.btCancelMenuItem1);
		btAdd1.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub

				String address = etAddress.getText().toString();
				String content = etContent.getText().toString();
				String timeStamp = new SimpleDateFormat("yyyy-MM-dd HH:mm")
						.format(new Date());

				WallAppItem item = new WallAppItem(currentMenuItem.id, content,
						timeStamp, address, null);
				if (currentMenuItem != null) {
					Long id = db.insertToNote(item);
					item.id = id.intValue();
				}
				appList.add(item);
				appAdapter.notifyDataSetChanged();
				// dialog.dismiss();
				dialog.cancel();
				etAddress.setText("");
				etContent.setText("");

			}
		});

		btCancel1.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				etAddress.setText("");
				etContent.setText("");
				dialog.cancel();
			}
		});
		dialog.show();
	}

	private OnCreateContextMenuListener createAppContextMenuListener = new OnCreateContextMenuListener() {

		@Override
		public void onCreateContextMenu(ContextMenu menu, View view,
				ContextMenuInfo menuInfo) {
			// TODO Auto-generated method stub
			AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) menuInfo;
			int index = info.position;
			menu.setHeaderTitle("Note Item");
			switch (index) {
			case 0:
				menu.add(1, 0, 0, "View on Map");
				return;
			default:
				menu.add(1, 1, 0, "Delete Note");
				break;
			}

		}
	};

	@Override
	public boolean onContextItemSelected(MenuItem item) {
		// TODO Auto-generated method stub
		AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item
				.getMenuInfo();
		int index = info.position;
		int groupId = item.getGroupId();
		if (index <= 0)
			return false;

		switch (groupId) {
		case 0:
			Toast.makeText(getApplicationContext(),
					"Delete Trip at position:" + index, Toast.LENGTH_SHORT)
					.show();
			WallMenuItem tripItem = menuList.get(index - 1);
			db.deleteNoteWithTripId(tripItem.id);
			db.deleteTripWithId(tripItem.id);
			menuList.remove(index - 1);
			if (currentMenuItem.id == tripItem.id) {
				if (menuList.size() > 0) {

					currentMenuItem = menuList.get(0);
					getAppList(currentMenuItem.id);
				} else {
					// Neu menu item la phan tu cuoi cung
					appList.clear();
					updateAppHeader();
				}
				appAdapter.notifyDataSetChanged();
			}
			reAnimation(0);
			menuAdapter.notifyDataSetChanged();
			break;
		case 1:

			if (item.getItemId() == 0) {
				Toast.makeText(getApplicationContext(), "View on Map ",
						Toast.LENGTH_SHORT).show();

			} else {
				Toast.makeText(getApplicationContext(),
						"Delete note at positon " + index, Toast.LENGTH_SHORT)
						.show();
				WallAppItem appItem = appList.get(index - 1);
				db.deleteNoteWithId(appItem.id);
				appList.remove(index - 1);
				appAdapter.notifyDataSetChanged();
			}
			break;
		default:
			break;
		}
		Log.i("context", "position:" + index + item.getTitle());

		return super.onContextItemSelected(item);
		// return true;
	}
}
